﻿using BLL;
using DevExpress.XtraEditors;
using DevExpress.XtraExport.Helpers;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using FastReport.Dialog;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 纺织贸易管理系统;

namespace 后整理管理系统.自定义类
{
    public class StockHelper
    {
        public List<StockTable> stocks { get; set; } = new List<StockTable>();
        public GridView MinxiGridview { get; set; } = new GridView();
        public GridView RollsGridview { get; set; } = new GridView();
        public List<danjumingxitable> danjumingxitables { get; set; } = new List<danjumingxitable>();
        public TextBox txtdanhao { get; set; } = new TextBox();
        /// <summary>
        /// 单据明细GridControl
        /// </summary>
        public DevExpress.XtraGrid.GridControl DetailgridControl { get; set; } = new DevExpress.XtraGrid.GridControl();
        /// <summary>
        /// 卷明细GridControl
        /// </summary>
        public DevExpress.XtraGrid.GridControl RollgridControl { get; set; } = new DevExpress.XtraGrid.GridControl();
        public DateEdit dateEdit1 { get; set; } = new DateEdit();
        public ButtonEdit txtkehu { get; set; } = new ButtonEdit();
        public List<JuanHaoTable> juanList { get; set; }
        /// <summary>
        /// 根据库存转换成单据明细
        /// </summary>
        /// <param name="stocks"></param>
        public void StockToDanjumingxi()
        {
            var i = MinxiGridview.FocusedRowHandle<0?0:MinxiGridview.FocusedRowHandle;
            
            //stockTables.AddRange(fm.pingzhong);
            foreach (var pingzhong in stocks)
            {
                if (danjumingxitables.Where(x =>x.rkdh==pingzhong.RKDH&& x.Bianhao == pingzhong.BH && x.ganghao == pingzhong.GH && x.houzhengli == pingzhong.houzhengli && x.yanse == pingzhong.YS && x.OrderNum == pingzhong.orderNum && x.kuanhao == pingzhong.kuanhao && x.ContractNum == pingzhong.ContractNum).Count() > 0)
                {
                    if (Tools.ShowMessageBox.ShowAskBox($"缸号:" + pingzhong.GH + $"\r\n编号:{pingzhong.BH}\r\n后整理:{pingzhong.houzhengli}\r\n颜色:{pingzhong.YS}\r\n已经存在信息！是否继续添加") == DialogResult.No)
                    {
                        continue;
                    }
                }
                danjumingxitables[i].bizhong = "人民币￥";
                danjumingxitables[i].Bianhao = pingzhong.BH;
                danjumingxitables[i].guige = pingzhong.GG;
                danjumingxitables[i].chengfeng = pingzhong.CF;
                danjumingxitables[i].pingming = pingzhong.PM;
                danjumingxitables[i].kezhong = pingzhong.KZ;
                danjumingxitables[i].menfu = pingzhong.MF;
                danjumingxitables[i].danwei = "米";
                danjumingxitables[i].ContractNum = pingzhong.ContractNum;
                danjumingxitables[i].CustomName = pingzhong.CustomName;
                danjumingxitables[i].OrderNum = pingzhong.orderNum;
                danjumingxitables[i].kuanhao = pingzhong.kuanhao;
                danjumingxitables[i].houzhengli = pingzhong.houzhengli;
                danjumingxitables[i].yanse = pingzhong.YS;
                danjumingxitables[i].Chengpingyanse = pingzhong.YS;
                danjumingxitables[i].ganghao = pingzhong.GH;
                danjumingxitables[i].chengpingjuanshu = pingzhong.JS;
                danjumingxitables[i].toupimishu = pingzhong.MS;
                danjumingxitables[i].chengpingmishu = pingzhong.MS;
                danjumingxitables[i].Kuwei = pingzhong.Kuwei;
                danjumingxitables[i].Huahao = pingzhong.Huahao;
                danjumingxitables[i].ColorNum = pingzhong.ColorNum;
                danjumingxitables[i].CustomerColorNum = pingzhong.CustomerColorNum;
                danjumingxitables[i].CustomerPingMing = pingzhong.CustomerPingMing;
                danjumingxitables[i].rq = dateEdit1.DateTime;
                danjumingxitables[i].IsHanshui = IsHanshuiModel.含税;
                danjumingxitables[i].suolv = pingzhong.ID;
                danjumingxitables[i].mashu = 100;
                danjumingxitables[i].rkdh = pingzhong.RKDH;
                //if (!string.IsNullOrWhiteSpace(pingzhong.IsCheckDone))
                //{
                //    danjumingxitables[i].IsDone = pingzhong.IsCheckDone.Contains("已");
                //}
                //else
                //{
                danjumingxitables[i].IsDone = true;
                //}
                danjumingxitables[i].offerid = pingzhong.LiuzhuanCard;
                danjumingxitables[i].hanshuidanjia = OrderDetailTableService.GetOneOrderDetailTable(x => x.OrderNum == pingzhong.orderNum && x.sampleNum == pingzhong.BH && x.Kuanhao == pingzhong.kuanhao
                && x.ColorNum == pingzhong.ColorNum && x.color == pingzhong.YS && x.Huahao == pingzhong.Huahao).price;
                danjumingxitables[i].hanshuiheji = danjumingxitables[i].hanshuidanjia * pingzhong.MS;
                i++;
                if (i == danjumingxitables.Count - 1)
                    for (int j = 0; j < 30; j++)
                    {
                        danjumingxitables.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(dateEdit1.Text) });
                    }
            }
            //  自动填写价格();
            DetailgridControl.DataSource = danjumingxitables;
            DetailgridControl.RefreshDataSource();
            MinxiGridview.CloseEditor();
            //  检查其他费用();
        }
        public void 自动填写价格()
        {
            if (AccessBLL.CheckAccess("销售价格填写"))
            {
                foreach (var mingxi in danjumingxitables)
                {
                    if (!string.IsNullOrEmpty(mingxi.pingming))
                    {
                        var dt = Connect.dbcontext.Queryable<DanjuTable>().LeftJoin<danjumingxitable>((x, y) => x.dh == y.danhao).Where((x, y) => x.ksmc == txtkehu.Text && y.houzhengli == mingxi.houzhengli).Select<danjumingxitable>().OrderByDescending(x => x.ID).ToList();

                        if (dt.Count > 0)
                        {
                            mingxi.hanshuidanjia = dt[0].hanshuidanjia;
                            mingxi.hanshuiheji = mingxi.hanshuidanjia * mingxi.toupimishu;
                        }
                    }
                }
            }
        }
        public void 检查其他费用()
        {
            foreach (var d in danjumingxitables.Where(x => x.OrderNum != null).Select(x => x.OrderNum).Distinct().ToList())
            {
                if (订单BLL.CheckOtherCost(d) == true)
                {
                    if (销售发货单BLL.CheckDanjuMingxiContainOtherCost(d) == false)
                    {
                        Tools.ShowMessageBox.ShowAskBox($"改订单号{d}存在其他费用！而且对账单还没体现过！");
                    }
                }
            }
        }
        public void SelectionChange(GridView gridView2)
        {
            //try
            //{
            foreach (var d in danjumingxitables)
            {
                d.chengpingmishu = 0;
                d.chengpingjuanshu = 0;
                d.toupimishu = 0;
            }
            var selectrolls = SelectHelper.GetSelectList<JuanHaoTable>(gridView2);
            foreach (var juan in selectrolls )
            {                
                var d = danjumingxitables.Where(x => x.ganghao == juan.GangHao && x.yanse == juan.yanse&& x.rkdh == juan.ReceiptNo&&x.houzhengli.Trim()==juan.Houzhengli.Trim()).ToList();
                  if (d.Count > 0)
                {
                    juan.Huahao = d[0].Huahao;
                    d[0].mashu = juan.MaShu;
                    d[0].OutboundUnit = juan.Danwei;
                    d[0].chengpingmishu += QueryTime.IsCalGive ? juan.biaoqianmishu + juan.JiaJian : juan.biaoqianmishu;
                    if (d[0].danwei == "米" && juan.Danwei == "米")
                    {
                        d[0].toupimishu = juan.MaShu != 0 ? d[0].chengpingmishu * (juan.MaShu / 100) : d[0].chengpingmishu;
                    }
                    else
                    {
                        if (d[0].danwei == "米" && juan.Danwei == "码")
                        {
                            d[0].toupimishu = juan.MaShu != 0 ? d[0].chengpingmishu * (juan.MaShu / 100) * (decimal)0.9144 : d[0].chengpingmishu * (decimal)0.9144;
                        }
                        else
                        {
                            if (d[0].danwei == "码" && juan.Danwei == "码")
                            {
                                d[0].toupimishu = juan.MaShu != 0 ? d[0].chengpingmishu * (juan.MaShu / 100) : d[0].chengpingmishu;
                            }
                            else
                            {

                                d[0].toupimishu = juan.MaShu != 0 ? d[0].chengpingmishu * (juan.MaShu / 100) / (decimal)0.9144 : d[0].chengpingmishu / (decimal)0.9144;
                            }
                        }
                    }
                    d[0].chengpingjuanshu++;
                }
            }
            foreach (var d in danjumingxitables)
            {
                d.hanshuiheji = d.hanshuidanjia * d.toupimishu;
            }
            danjumingxitables.ForEach(x => x.IsDone = !string.IsNullOrEmpty(x.pingming));
            foreach(var item in juanList )
            {
               if(selectrolls.FirstOrDefault (x=>x.ID==item.ID )==null )
                {
                    var mingxi = danjumingxitables.FirstOrDefault(x => x.ganghao == item.GangHao && x.offerid == item.CustomerPingMing);
                    ///挑出来没有全发的缸号                          
                    if (mingxi != null)
                    {
                        //没有全发的标识未未发完                              
                        mingxi.IsDone = false;
                    }
                }
            }
            ////如果全部勾上的判断一下 该库存信息是不是已经检验完毕 检验完毕的标识已发完
            //if (stockTables.Count > 0)
            //{
            //    foreach (var mingxi in danjumingxitables.Where(x => x.IsDone == true))
            //    {
            //        var s = stockTables.First(x => x.ID == (int)mingxi.suolv);
            //        if (s != null)
            //        {
            //          if(mingxi.chengpingjuanshu<s.JS)
            //            {
            //                mingxi.IsDone = false;
            //            }

            //        }
            //    }
            //}
            DetailgridControl.RefreshDataSource();
            //}
            //catch (Exception ex)
            //{
            //   Tools. ShowMessageBox.ShowErrorBox(ex.Message);
            //}
        }
        public List<JuanHaoTable> 加载卷(StockTable stock)
        {
            return Connect.dbcontext.Queryable<JuanHaoTable >().Where (x => x.GangHao == stock.GH && x.yanse == stock.YS&&x.ReceiptNo==stock.RKDH   && x.state == 0 && x.CustomerName == stock.CustomName && x.Ckmc == stock.CKMC).OrderBy(x => x.PiHao).ToList();
        }
        public void 加载卷(List<JuanHaoTable> juanList, DevExpress.XtraGrid.GridControl gridControl2, string stockname)
        {
            juanList.Clear();
            foreach (var d in danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)))
            {
                //var juans = JuanHaoTableService.GetJuanHaoTablelst(x => x.Ckmc == ((int)d.suolv).ToString() && x.state == 0);
                //if (juans.Count > 0)
                //{
                //    juanList.AddRange(juans);
                //}
                //else
                //{
                // var juans = JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerName == txtkehu.Text && x.yanse == d.yanse && x.GangHao == d.ganghao && x.state == 0);
                //if (StockTableService.GetOneStockTable(x => x.ID == (int)d.suolv).yijianmishu != 0)
                //{
                juanList.AddRange(JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerName == txtkehu.Text && x.yanse == d.yanse && x.GangHao == d.ganghao && x.state == 0 && x.Ckmc == stockname &&x.ReceiptNo==d.rkdh&&x.Houzhengli==d.houzhengli));
                //}
                //}
                if (juanList.Count == 0)
                {
                    d.chengpingmishu = d.toupimishu;
                    d.chengpingjuanshu = d.chengpingjuanshu;
                }
            }
            juanList = juanList.OrderBy(x => x.GangHao).ThenBy(x => x.PiHao).ToList();
            gridControl2.DataSource = juanList;
            gridControl2.RefreshDataSource();
        }

        public void CreateDanjuWithDanjumingxi(SelectParms parms)
        {
            //初始化单据信息
            if (parms.StockTables !=null)
            {
                parms.Txtckmc.Text = parms.StockTables[0].CKMC;
                parms.Txtkehu.Text = parms.StockTables[0].CustomName;
                var lxr = LXRService.GetOneLXR(x => x.MC == parms.Txtkehu.Text);
                if (lxr != null)
                {
                    parms.Danju.ksbh = lxr.BH;
                    parms.Danju.ksmc = lxr.MC;
                }
                stocks = parms.StockTables;
            }
           
           StockToDanjumingxi();//生成单据明细
            if (parms.Juanhaos != null)
            {
                加载卷(parms.Juanhaos, DetailgridControl, parms.Txtckmc.Text);
                //把所有的细码都打上勾
                SetAllSelect();
            }
        }
        /// 把所有的细码全部选中
        /// </summary>
        private void SetAllSelect()
        {
            for (int rowindex = 0; rowindex < RollsGridview.RowCount; rowindex++)
            {
                RollsGridview.SelectRow(rowindex);
            }
        }
        /// <summary>
        /// 检查所选细码是否有不通挂码
        /// </summary>
        /// <param name="juanHaos"></param>
        /// <returns></returns>
        public static Boolean CheckMashu(List<JuanHaoTable> juanHaos)
        {
            return juanHaos.Select(x => x.MaShu).Distinct().ToList().Count > 1;
        }
        /// <summary>
        /// 检查所选细码是否有不通挂码
        /// </summary>
        /// <param name="juanHaos"></param>
        /// <returns></returns>
        public static Boolean CheckDanWei(List<JuanHaoTable> juanHaos)
        {
            return juanHaos.Select(x => x.Danwei).Distinct().ToList().Count > 1;
        }
        public void CreateDanjuWithJuanhaotable(SelectParms parms)
        {
            //初始化单据信息
            if (parms.StockTables.Count > 0)
            {
                parms.Txtckmc.Text = parms.StockTables[0].CKMC;
                txtkehu.Text = parms.StockTables[0].CustomName;
                var lxr = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
                if (lxr != null)
                {
                    parms.Danju.ksbh = lxr.BH;
                    parms.Danju.ksmc = lxr.MC;
                }
            }
            StockToDanjumingxi();//生成单据明细
            juanList = JsonConvert.DeserializeObject<List<JuanHaoTable>>(JsonConvert.SerializeObject(parms.Juanhaos));
            parms.Juanhaos.Clear();
            RollgridControl.DataSource = juanList;
            RollgridControl.RefreshDataSource();
            //把所有的细码都打上勾
            SetAllSelect();
        }
        public void 重新加载卷(List<JuanHaoTable> juanList, DevExpress.XtraGrid.GridControl gridControl2, string stockname)
        {
            try
            {
                foreach (var d in danjumingxitables.Where(x => !string.IsNullOrWhiteSpace(x.pingming)))
                {
                    //JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerName == txtkehu.Text && x.yanse == d.yanse && x.GangHao == d.ganghao && x.state == 0&&x.Ckmc==stockname )
                    var juans = JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerName == txtkehu.Text && x.yanse == d.yanse && x.GangHao == d.ganghao && x.Ckmc == stockname);
                    foreach (var j in juans)
                    {
                        if (juanList.FirstOrDefault(x => x.JuanHao == j.JuanHao) == null)
                        {
                            juanList.Add(j);
                        }
                    }
                    if (juanList.Count == 0)
                    {
                        d.chengpingmishu = d.toupimishu;
                        d.chengpingjuanshu = 1;
                    }
                }
                juanList = juanList.OrderBy(x => x.GangHao).ThenBy(x => x.PiHao).ToList();
                gridControl2.DataSource = juanList;
                gridControl2.RefreshDataSource();
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("重新加载卷的时候发送了错误：" + ex.Message);
            }
        }
    }
}
